//
//  MTSendRedpackViewController.swift
//  MT
//
//  Created by ooops on 2019/12/22.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import GrowingTextView
import RxSwift
import RxCocoa

public typealias RedpacketCallBack = (Bool) -> Swift.Void

class MTSendRedpackViewController: BaseViewController {
    
    
    /// 红包请求参数
    private var requestParam: [String : Any]?
    private let disposedBag = DisposeBag()
    private let wordCount: Int = 12
    private let provider: MTProvider = MTProvider<MTClubApi>()
    
    /// 数据是否通过验证
    private var validateValues: Bool
    
    /// 每个人分到的h钻石是否大于 1
    private var moneyValueMoreThanOne: Bool
    private var redpackMessage: String = "新年快乐！万事如意！"
    
    /// 会话对象
    private var conversationType: JMSGConversationType = .single
    
    private var redCallBack: RedpacketCallBack?
    /// 是否是聚会任务红包
    private var isPartyTaskRedpack: Bool = false
    
    override init() {
        self.validateValues = false
        self.moneyValueMoreThanOne = false
        super.init()
    }
    
    
    /// 聚会任务群主发红包专用接口
    /// - Parameters:
    ///   - conversation: conversation description
    ///   - partyTaskId: 聚会任务ID
    ///   - callBack: callBack description
    convenience init(_ conversation: JMSGConversation, partyTaskId: Int, callBack: @escaping RedpacketCallBack) {
        self.init()
        self.redCallBack = callBack
        self.isPartyTaskRedpack = true
        var requestParam: [String : Any] = ["partyTaskId": partyTaskId,
                                            "count": 1,
                                            "groupId": "",
                                            "message": "新年快乐！万事如意！",
                                            "money": 1,
                                            "roomId": "",
                                            "type": 0,
                                            "userName": ""]
        
        conversationType = conversation.conversationType
        
        requestParam.updateValue(conversationType.rawValue, forKey: "type")

        if let group = conversation.target as? JMSGGroup {
            requestParam.updateValue(group.gid, forKey: "groupId")
        } else if let user: JMSGUser = conversation.target as? JMSGUser {
            requestParam.updateValue(user.username, forKey: "userName")
        } else {
            let chat: JMSGChatRoom = conversation.target as! JMSGChatRoom
            requestParam.updateValue(chat.roomID, forKey: "roomId")
        }
        self.requestParam = requestParam
    }
    
    /// 初始化发送红包界面
    /// - Parameters:
    ///   - conversation: 会话列表
    ///   - callBack: 发送回调
    convenience init(_ conversation: JMSGConversation, callBack: @escaping RedpacketCallBack) {
        self.init()
        self.redCallBack = callBack
        var requestParam: [String : Any] = ["count": 1,
                                            "groupId": "",
                                            "message": "新年快乐！万事如意！",
                                            "money": 1,
                                            "roomId": "",
                                            "type": 0,
                                            "userName": ""]
        
        conversationType = conversation.conversationType
        
        requestParam.updateValue(conversationType.rawValue, forKey: "type")

        if let group = conversation.target as? JMSGGroup {
            requestParam.updateValue(group.gid, forKey: "groupId")
        } else if let user: JMSGUser = conversation.target as? JMSGUser {
            requestParam.updateValue(user.username, forKey: "userName")
        } else {
            let chat: JMSGChatRoom = conversation.target as! JMSGChatRoom
            requestParam.updateValue(chat.roomID, forKey: "roomId")
        }
        self.requestParam = requestParam
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    lazy var closeBtn: UIButton = {
        let close = UIButton(type: .custom)
        close.setTitle("关闭", for: .normal)
        close.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        close.titleLabel?.font = PingFangSCMediumFont(16)
        close.addTarget(self, action: #selector(MTSendRedpackViewController.close), for: .touchUpInside)
        return close
    }()
    
    lazy var moneyCount: MTSendRedpackInputView = {
        let v = MTSendRedpackInputView()
        v.placeholder = "0"
        v.preTips = "总金额"
        v.endTips = "钻石"
        v.txfKeyboardType = .numberPad
        return v
    }()
    
    lazy var redpackCount: MTSendRedpackInputView = {
        let v = MTSendRedpackInputView()
        v.placeholder = "填写个数"
        v.preTips = "红包个数"
        v.endTips = "个"
        v.txfKeyboardType = .numberPad
        return v
    }()
    
    lazy var redpackMessageView: GrowingTextView = {
        let textView = GrowingTextView()
        textView.frame = CGRect(x: 54, y: 190, width: 300, height: 100)
        textView.layer.cornerRadius = 3.0
        textView.placeholder = "新年快乐！万事如意！"
        textView.font = UIFont.systemFont(ofSize: 15)
        textView.maxLength = 16
        textView.delegate = self
        textView.minHeight = 100
        textView.maxHeight = 100
        return textView
    }()
    
    lazy var wordCountTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(14)
        l.textColor = UIColor.redpack.x5d5d5d
        l.text = "0/\(wordCount)"
        l.textAlignment = .right
        return l
    }()
    
    lazy var redpackMessageLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(16)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "祝福语"
        l.sizeToFit()
        return l
    }()
    
    lazy var sendRedpackButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("塞钻石进红包", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.isUserInteractionEnabled = false
        btn.layer.cornerRadius = 22
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(sendRedpack), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0xf4f4f4)
        setupUI()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler))
        view.addGestureRecognizer(tapGesture)
        
        validateData()
        
        if self.conversationType == .single {
            redpackCount.snp.updateConstraints { (make) in
                make.top.equalTo(moneyCount.snp.bottom).offset(0)
                make.centerX.equalToSuperview()
                make.left.equalTo(moneyCount)
                make.right.equalTo(moneyCount)
                make.height.equalTo(0)
            }
            
            redpackCount.isHidden = true
        }
    }
    
    
    /// 数据验证
    private func validateData() {
        let canSend = Observable.combineLatest(moneyCount.contentTextField.rx.text.orEmpty, redpackCount.contentTextField.rx.text.orEmpty) { money, count -> (Bool, Bool) in
            let moneyIntValue: Int = Int(money) ?? 0, redpackCountValue: Int = Int(count) ?? 0
            
            /// 个人无需红包数量
            if self.conversationType == .single {
               return (moneyIntValue > 0, true)
            }
            /// 俱乐部红包 / 广场红包 判断红包数量
            if redpackCountValue == 0 {
                return (moneyIntValue > 0 && redpackCountValue > 0, false)
            }
            let canSend: Bool = (moneyIntValue / redpackCountValue) >= 1
            return (moneyIntValue > 0 && redpackCountValue > 0, canSend)
        }
        
        _ = redpackMessageView.rx.text.orEmpty.subscribe { [weak self] (element) in
            guard let weakSelf = self else { return }
            _ = canSend.subscribe { (ele) in
                weakSelf.validateValues = ele.element!.0
                weakSelf.moneyValueMoreThanOne = ele.element!.1
                
                if let count = element.element?.count, count > 0 {
                    weakSelf.redpackMessage = element.element!
                }
                
                if weakSelf.validateValues { //  && weakSelf.moneyValueMoreThanOne
                    weakSelf.sendRedpackButton.isUserInteractionEnabled = true
                    weakSelf.sendRedpackButton.backgroundColor = UIColor.theme.main
                } else {
                    weakSelf.sendRedpackButton.isUserInteractionEnabled = false
                    weakSelf.sendRedpackButton.backgroundColor = UIColor.redpack.x5d5d5d
                }
            }
        }
    }
    
    @objc private func tapGestureHandler() {
        view.endEditing(true)
    }
    
    @objc private func sendRedpack() {
        if let redpacketCount = moneyCount.textValue, let redpacketMoney = Int(redpacketCount) {
            MTClubTool.config(provider: provider, complete: {[weak self] (model) in
                guard let weakSelf = self else { return }
                guard let ticketAmount = model?.result?.ticketAmount else { return }
                /// 查询用户余额
                if (model?.code == 200 && redpacketMoney > ticketAmount) || model?.code == 600 {
                    UIAlertController.rx.show(in: weakSelf, title: "提示", message: "钻石余额不足，请充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                        /// 去充值的引导
                        if index == 1 {
                            if UserDefaults.AppValidate.isValidate.storedBool == false {
                                let c = MTPaymentViewController()
                                weakSelf.navigationController?.pushViewController(c, animated: true)
                            } else {
                                let c = MTInAppPurchasesViewController()
                                weakSelf.navigationController?.pushViewController(c, animated: true)
                            }
                        }
                    })
                    .disposed(by: globalDisposedBag)
                } else {
                    
                    guard var request = weakSelf.requestParam else { return }
                    
                    request.updateValue(weakSelf.redpackMessage, forKey: "message")
                    request.updateValue(weakSelf.moneyCount.textValue!, forKey: "money")
                    if weakSelf.conversationType != .single {
                        request.updateValue(weakSelf.redpackCount.textValue!, forKey: "count")
                    }
                    
                    debugPrint("redpackrequestparam", request)
                    
                    
                    if weakSelf.moneyValueMoreThanOne == false && weakSelf.conversationType != .single {
                        MBProgressHUD_JChat.show(text: "红包个数不能大于金额", view: weakSelf.view)
                        return
                    }
                    
                    MTRedpackTool.default.sendRedpack(request) { [weak self] (model, isSuccess) in
                        guard let weakSelf = self else { return }
                        //let d = model
                        if model?.code == 600 {
                            MBProgressHUD_JChat.show(text: model?.message ?? "余额不足", view: weakSelf.view, 1)
                            return
                        }
                        
                        if model?.code == 900 {
                            MBProgressHUD_JChat.show(text: weakSelf.isPartyTaskRedpack ? "聚会任务群已解散" : "俱乐部已解散", view: weakSelf.view, 1)
                            return
                        }
                        
                        if isSuccess {
                            weakSelf.dismiss(animated: true, completion: nil)
                            weakSelf.redCallBack?(true)
                        }
                    }
                }
                
            }) { (error) in
                
            }
        }
        
    }
    
    
    private func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeBtn)
        self.title = "发红包"
        
        view.addSubview(moneyCount)
        view.addSubview(redpackCount)
        view.addSubview(redpackMessageLabel)
        view.addSubview(redpackMessageView)
        view.addSubview(wordCountTipLabel)
        view.addSubview(sendRedpackButton)
        
        moneyCount.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight + 55)
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.height.equalTo(64)
        }
        
        redpackCount.snp.makeConstraints { (make) in
            make.top.equalTo(moneyCount.snp.bottom).offset(25)
            make.centerX.equalToSuperview()
            make.left.equalTo(moneyCount)
            make.right.equalTo(moneyCount)
            make.height.equalTo(64)
        }
        
        redpackMessageLabel.snp.makeConstraints { (make) in
            make.top.equalTo(redpackCount.snp.bottom).offset(25)
            make.left.equalTo(moneyCount).offset(10)
            make.right.equalTo(moneyCount)
        }
        
        redpackMessageView.snp.makeConstraints { (make) in
            make.top.equalTo(redpackMessageLabel.snp.bottom).offset(9)
            make.left.equalTo(moneyCount)
            make.right.equalTo(moneyCount)
            make.height.equalTo(100)
        }
        
        wordCountTipLabel.snp.makeConstraints { (make) in
            make.right.equalTo(redpackMessageView).offset(-5)
            make.bottom.equalTo(redpackMessageView)
            make.width.equalTo(40)
            make.height.equalTo(20)
        }
        
        sendRedpackButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalTo(210)
            make.height.equalTo(44)
            make.bottom.equalToSuperview().offset(-ScreenBottomExtraOffset - 43)
        }
    }
    
    
    // MARK: 关闭按钮
    @objc private func close() {
        self.dismiss(animated: true, completion: nil)
    }

}

extension MTSendRedpackViewController: GrowingTextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        wordCountTipLabel.text = "\(textView.text.count)/\(wordCount)"
    }
}
